# coding=utf-8
import sys
from tabulate import tabulate
from staff.config import Filter as fld, Staff as stf, Message as msg, \
    Sort as srt, LenFun as len_fun

staff_list = stf.staff_list   # 员工信息列表


class Action(object):

    def add_staff_info(self, info):
        # 新建员工信息
        name, number, entry_date, branch, position = \
            info[1], info[2], info[3], info[4], info[5]
        new_staff = [name, number, entry_date, branch, position]
        staff_list.append(new_staff)
        print('添加员工信息成功！')

    def del_staff_info(self, info):
        # 删除员工信息
        number = info[1]
        res = self.get_staff(number)
        if res:
            staff_list.remove(res)
            print(f'成功删除工号为{number}的员工信息!')
        else:
            print(f'{number} 不存在，请确认后重试！')
            return []

    def mod_staff_info(self, info):
        # 修改员工信息
        number = info[1]
        res = self.get_staff(number)
        if res:
            mod_type = info[2]
            new_param = info[3]

            index = fld.fields.index(mod_type)
            res[index] = new_param
            print(f'修改{mod_type}成功!')
        else:
            print(f'{number} 不存在，请确认后重试！')
            return []

    def get_staff_info(self, info):
        # 查询员工信息
        number = info[1]
        staff_info = self.get_staff(number)
        if not staff_info:
            print(staff_info)
        else:
            self.tabulate_print([staff_info])
        return staff_info

    def list_staff_info(self, info):
        # 遍历员工信息(支持排序)
        listed_list = []
        if len(info) == len_fun.ALL:
            # 如果只输入了list，那么打印列表中所有员工信息
            self.print_list_info()
            return staff_list
        elif len(info) == len_fun.FILTER_SORT:
            # 说明进行了过滤 or 排序 or 过滤和排序操作
            info = info[1].split(",")
            if len(info) == len_fun.FILTER_OR_SORT:
                # 说明进行了过滤 or 排序其中一个
                info = info[0].split(":")
                med = info[0]
                if med in fld.fields:
                    listed_list = self.list_info(info, med)
                    self.tabulate_print(listed_list)
                    return listed_list
                elif med == srt.SORT:
                    sort_field = info[1]
                    if sort_field in fld.fields:
                        sorted_list = self.sort_logic_fun(info, staff_list)
                        self.tabulate_print(sorted_list)
                        return sorted_list
                    else:
                        self.error_exit()
                else:
                    self.error_exit()

            elif len(info) == len_fun.FILTER_AND_SORT:
                # 说明过滤和排序都执行了, 先过滤后排序
                filter_info = info[0].split(":")
                med = filter_info[0]
                if med in fld.fields:
                    listed_list = self.list_info(filter_info, med)

                sort_info = info[1].split(":")
                med = sort_info[0]
                if med == srt.SORT:
                    sort_field = sort_info[1]
                    if sort_field in fld.fields:
                        sorted_list = self.sort_logic_fun(
                            sort_info, listed_list)
                        self.tabulate_print(sorted_list)
                        return sorted_list
        else:
            self.error_exit()

    def exit_staff_info(self, info):
        # 退出系统
        print('期待您下次使用！')
        sys.exit(0)

    def help_staff_info(self, info):
        # 打印帮助信息
        if len(info) == 1:
            print(msg.HELP_MSG)
            return msg.HELP_MSG
        elif len(info) == 2:
            handle = {
                'add': msg.HELP_ADD,
                'del': msg.HELP_DEL,
                'mod': msg.HELP_MOD,
                'get': msg.HELP_GET,
                'list': msg.HELP_LIST,
            }
            action = info[1]
            help_info = handle[action]
            print(help_info)
            return help_info

    @staticmethod
    def error_exit():
        print("操作错误,请确认后重试！")
        return

    def print_list_info(self, local_staff_list=None):
        if not local_staff_list:
            local_staff_list = staff_list
        self.tabulate_print(local_staff_list)

    @staticmethod
    def list_info(info, med):
        listed_list = []

        list_field = info[1]  # 获取过滤的字段
        index = fld.fields.index(med)  # 获取过类型的索引

        for staff in staff_list:
            if list_field == staff[index]:
                listed_list.append(staff)
        return listed_list

    def sort_logic_fun(self, info, sort_list):
        sort_field = info[1]
        sort_method = None
        if len(info) == 3:
            sort_method = info[2]
        elif len(info) == 2:
            sort_method = srt.ASC

        sorted_list = self.sort_function(sort_list, sort_field, sort_method)
        return sorted_list

    @staticmethod
    def sort_function(listed_list, sort_field, sort_method):
        field_info = {
            'name': 0,
            'number': 1,
            'date': 2,
            'branch': 3,
            'position': 4,
        }
        index = field_info[sort_field]
        reverse = None
        if sort_method == srt.DESC:
            reverse = True
        elif sort_method == srt.ASC:
            # 当排序方式为ASC或者不传时,默认为升序
            reverse = False

        sorted_list = sorted(listed_list, key=lambda line: line[index],
                             reverse=reverse)
        return sorted_list

    @staticmethod
    def get_staff(number):
        for staff in staff_list:
            if staff[1] == number:
                return staff
        return []

    @staticmethod
    def tabulate_print(table):
        # 格式化打印
        print(tabulate(table, headers=stf.headers, tablefmt='grid'))
